package com.lingshi.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.lingshi.common.service.FileService;
import org.apache.commons.io.FilenameUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Value;

import java.io.ByteArrayInputStream;
import java.util.List;

@DubboService
public class ShoppingFileServiceImpl implements FileService {
    @Value("${upload.endpoint}")
    private String endpoint;
    @Value("${upload.bucket}")
    private String bucketName;
    @Value("${upload.accessKey}")
    private String accessKey;
    @Value("${upload.secretKey}")
    private String secretKey;
    @Value("${upload.serverUrl}")
    private String serverUrl;

    public OSS initOSS(){
        return new OSSClientBuilder().build(endpoint,accessKey,secretKey);
    }

    @Override
    public String uploadImage(byte[] fileBytes, String fileName) {
        OSS oss = initOSS();
        try{
            //获取文件的后缀
            String extension = FilenameUtils.getExtension(fileName);

            //生成心的文件名称
            String newFileName = RandomUtil.randomString(20);

            newFileName = newFileName + StrUtil.DOT +extension;
            System.out.println("newFileName = " + newFileName);
            ByteArrayInputStream inputStream = new ByteArrayInputStream(fileBytes);

            //上传0ss文件
            oss.putObject(bucketName,newFileName,inputStream);

            //拼接完整的文件服务地址
            return serverUrl + StrUtil.SLASH + newFileName;

        }finally {
            oss.shutdown();
        }

    }

    @Override
    public void delete(String filePath) {
        OSS oss = initOSS();
        try{
            List<String> list = StrUtil.split(filePath, "/");
            String fileName = CollUtil.getLast(list);
            //删除oss文件
            oss.deleteObject(bucketName,fileName);
        }finally {
            oss.shutdown();
        }
    }
}
